import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import '../common/logger.dart';
import '../common/sharedPreferences_helper.dart';
import '../common/utils.dart';
import '../model/base_response.dart';
import '../model/community_video_model.dart';
import '../model/video_info.dart';

class VideoRelatedController extends GetxController {
  final int relateId;
  var videoInfo = Rx<VideoInfo?>(null);
  var videoList = <IssueList>[].obs;
  var id = 0.obs;
  final scrollController = ScrollController();

  VideoRelatedController(this.relateId);

  @override
  void onInit() {
    super.onInit();
    id.value = relateId;
    loadData();
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }

  void scrollToTop() {
    scrollController.jumpTo(0.0);
  }

  Future<void> loadData() async {
    await loadVideoDetail();
    await loadRelateVideoList();
  }

  Future<void> loadRelateVideoList() async {
    Dio dio = Dio();
    var params = {"id": id.value};
    final url = "http://baobab.kaiyanapp.com/api/v4/video/related";
    final response = await dio.get(url, queryParameters: params);
    var model = CommunityVideoModel.fromJson(response.data);
    final dataList = model.itemList!.where((x) => x.type == "videoSmallCard").toList();
    videoList.addAll(dataList);
  }

  Future<void> loadVideoDetail() async {
    try {
      final accessToken = SharedPreferencesHelper.getString('eyepetizer_accessToken');
      if (!isEmpty(accessToken)) {
        Dio dio = Dio();
        final url = "https://proxy.eyepetizer.net/v1/content/item/get_item_detail_v2";
        final data = {"resource_id": id.value, "resource_type": 'pgc_video'};
        dio.options.headers["x-thefair-appid"] = 'xfpa44crf2p70lk8';
        dio.options.headers["x-thefair-auth"] = accessToken;
        dio.options.headers["x-thefair-forward-host"] = 'https://api.eyepetizer.net';
        dio.options.headers["x-thefair-cid"] = '4dfa58afb261d6b94b2f1e9c9c7c78fd';
        dio.options.headers["x-thefair-ua"] = 'EYEPETIZER_UNIAPP_H5/100000 (android;android;OS_VERSION_UNKNOWN;zh-Hans-CN;h5;1.0.0;cn-bj;SOURCE_UNKNOWN;4dfa58afb261d6b94b2f1e9c9c7c78fd;4096*2304;NETWORK_UNKNOWN) native/1.0';
        dio.options.headers["content-type"] = 'application/x-www-form-urlencoded';
        final response = await dio.post(url, data: data);
        final result = BaseResponse.fromJson(response.data);
        videoInfo.value = VideoInfo.fromJson(result.result);
      }
    } catch (e, stackTrace) {
      logger.e("$e, $stackTrace");
    }
  }
}